package leetcode.code1034;

import leetcode.helper.MaxDebug;

public class Solution extends S1034 {

	private int rowLen;
	private int colLen;
	private boolean[][] colored;
	private int colorSrc;
	private int color2;
	private int[][] grid;

	@Override
	public int[][] colorBorder(int[][] grid, int row, int col, int color) {
		this.rowLen = grid.length;
		this.colLen = grid[0].length;
		this.colored = new boolean[rowLen][colLen];// 检查过
		this.colorSrc = grid[row][col];// 联通色
		this.color2 = color;// 涂色成color2
		this.grid = grid;
		this.f(row, col);
		return grid;
	}

	private void f(int row, int col) {
		if (row >= 0 && row < rowLen && col >= 0 && col < colLen && !this.colored[row][col]
				&& grid[row][col] == this.colorSrc) {// 未检查过的 && 联通区域
			if (this.isRange(row, col)) {// 是不是边界
				grid[row][col] = color2;// 是边界就着色
			}
			this.colored[row][col] = true;// 访问过
			this.f(row + 1, col);
			this.f(row - 1, col);
			this.f(row, col + 1);
			this.f(row, col - 1);
		}
	}

	private boolean isRange(int row, int col) {
		if (this.check(row + 1, col) || this.check(row - 1, col) || this.check(row, col + 1) || this.check(row, col - 1)) {
			return true;
		}
		return false;
	}

	private boolean check(int row, int col) {
		if (row >= rowLen || row < 0 || col >= colLen || col < 0) {// 越界是边界
			return true;
		}
		if (this.grid[row][col] != this.colorSrc && !this.colored[row][col]) {// 颜色与原色不同 && 是未检查过的位置
			return true;
		}
		return false;
	}

	public static void main(String[] args) {
		Solution so = new Solution();
		MaxDebug.debug14(so);

	}

}
